package org.os.framework.context.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 跨域配置
 * 
 * @author
 */
@Slf4j
@Data
@ConfigurationProperties(prefix = "spring.cross-origin")
@Configuration
public class CrossOriginConfig {

    /**
     * 可访问源
     */
    private String origin = "*";

    /**
     * 允许头部报文
     */
    private String allowedHeader = "*";

    /**
     * 方法
     */
    private String method = "*";

    /**
     * 资源注册，正则
     */
    private String sourcePattern = "/**";

    /**
     * 优先级
     */
    private Integer order = 0;

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        log.info("已启用跨域配置：{}", this);
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern(origin);
        config.addAllowedHeader(allowedHeader);
        config.addAllowedMethod(method);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration(sourcePattern, config);
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(source));
        bean.setOrder(order);
        return bean;
    }

}
